package uk.ac.glasgow.demosocs.store;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import uk.ac.glasgow.demosocs.impl.ElectionImpl;

/**
 * @author Bilal, Tsvetelina
 * 
 * This class, reads and writes objects of type election to a file.
 * As a result the election state is permanently saved, when the program
 * is restarted.
 * 
 */

/** A simple file based implementation of a store for users. */
public class ElectionStore  {

	private Map<String,ElectionImpl> elections;
	

	private File storeFile;
	
	/**
	 * Constructs a new election store in the specified file location.
	 * @param fileName
	 */
	public ElectionStore(String fileName){
		storeFile = new File(fileName);
		if (storeFile.exists()){
			try {
				ObjectInputStream ois = 
					new ObjectInputStream(new FileInputStream(storeFile));
				elections = (Map<String,ElectionImpl>)ois.readObject();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		else
			this.elections = new HashMap<String,ElectionImpl>();
	}
	/**
	 * Adds an election to the election store file.
	 * @param election
	 * 			The election ID, e.g. EID1
	 */
	public void addElection(ElectionImpl election) {
		String electionID = election.getEID();
		elections.put(electionID, election);
		
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(storeFile));
			oos.writeObject(elections);		// <--- Changed to users, used to be storeFile.
			oos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * This method finds a specified election from the election
	 * store.
	 * 
	 * @param electionId
	 * 			The election id e.g. EID1
	 * @return Election e
	 * 			null if know election matches election ID
	 */
	public ElectionImpl getElection(String electionId) {
		ElectionImpl e = elections.get(electionId);
		if (e.getEID().equals(electionId))
			return e;
		else return null;
	}
	
	public Map<String, ElectionImpl> getElections() {
		return elections;
	}

	public void setElections(Map<String, ElectionImpl> elections) {
		this.elections = elections;
	}
	


}
